package com.example.deploysinggle.test1.common.postconstruct;

import com.example.deploysinggle.test1.mybagenera.entity.ClientAuth;
import com.example.deploysinggle.test1.mybagenera.entity.ClientAuthExample;
import com.example.deploysinggle.test1.mybagenera.mapper.ClientAuthMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/12/15 19:28
 */
@Component
public class CommonCache {

    @Autowired
    private ClientAuthMapper clientAuthMapper;
    //注入mapper  每次需要重启才能生效的缓存
    private static  Map<Integer, List<String>>  REQ_URL_MAP = new HashMap<>();
    //计时器调研
    private static ScheduledExecutorService  scheduler = Executors.newScheduledThreadPool(1);

    @PostConstruct
    public void init() {
        loadUrl();
        //定时任务调用
        startSchedule();
    }

    private void loadUrl() {
        REQ_URL_MAP.clear();
        Map<Integer, List<String>> map = getList().stream().collect(Collectors.groupingBy(ClientAuth::getId, Collectors.mapping(ClientAuth::getReqUrl, Collectors.toList())));
        REQ_URL_MAP.putAll(map);

    }

    private void startSchedule() {
        scheduler.scheduleAtFixedRate(this::loadUrl, 0, 30, TimeUnit.MINUTES);
    }

    // 这个应该是从数据库拿到的
    private List<ClientAuth> getList() {
//        List<Aa> aa = new ArrayList<>();
//        aa.add(Aa.builder().id(1).url("/test1").build());
//        aa.add(Aa.builder().id(1).url("/bb").build());
//        aa.add(Aa.builder().id(2).url("/cc").build());
//        aa.add(Aa.builder().id(2).url("/dd").build());
         List<ClientAuth> clientAuths = clientAuthMapper.selectByExample(new ClientAuthExample());
        return clientAuths;
    }

    public static Map<Integer, List<String>> getUrlMap() {
        return REQ_URL_MAP;
    }

    @PreDestroy
    public void destory() {
        if (scheduler != null) {
            scheduler.shutdown();
        }
    }

}
